//
//  SQBRechargeViewController.m
//  SP2P
//
//  Created by 吴建东 on 16/6/7.
//  Copyright © 2016年 EIMS. All rights reserved.
//

#import "SQBRechargeViewController.h"
#import <BaoFooPay/BaoFooPay.h>
#import "LimitTableViewController.h"
#import "RechargeVerifyViewController.h"
#import <FUMobilePay/FUMobilePay.h>


@interface SQBRechargeViewController ()<HTTPClientDelegate,BaofooSdkDelegate,UITextFieldDelegate,UIAlertViewDelegate,FYPayDelegate> {
    BOOL _isBalanceSelect;
    BOOL _flag;
    CGFloat _mindHeight;
}
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UILabel *typeValue;
@property (weak, nonatomic) IBOutlet UIImageView *typeImageView;
@property (weak, nonatomic) IBOutlet UILabel *amoutValue;
@property (weak, nonatomic) IBOutlet UITextField *amoutTextField;
@property (weak, nonatomic) IBOutlet UILabel *moneyTypeValue;
@property (weak, nonatomic) IBOutlet ClickButton *rechargeButton;
@property (weak, nonatomic) IBOutlet UIButton *balanceButton;
@property (weak, nonatomic) IBOutlet UIButton *sqbButton;
@property (weak, nonatomic) IBOutlet UILabel *remindLabel;
@property (weak, nonatomic) IBOutlet UILabel *cardTypeLabel;
@property (weak, nonatomic) IBOutlet UIImageView *bankImageView;
@property (weak, nonatomic) IBOutlet UILabel *bankNameLabel;
@property (weak, nonatomic) IBOutlet UILabel *bankCardLabel;
@property (weak, nonatomic) IBOutlet UIView *limitView;
@property (weak, nonatomic) IBOutlet UILabel *limitLabel;
@property (weak, nonatomic) IBOutlet UIView *selectToppView;
@property (weak, nonatomic) IBOutlet UIView *toppNumView;

@property (nonatomic, strong) NetWorkClient *requestClient;
@property (nonatomic, assign) BOOL          isLoading;
@property (nonatomic, assign) NSInteger     requestType;

/**
 *  1 畅捷充值  2 富友充值
 */
@property (nonatomic, assign) NSInteger rechargeAppType;

@end

@implementation SQBRechargeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    _flag = 1;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    [self initNavBarTitle:@"充值" andLeftItemName:@"返回" andRightItemName:@"额度表"];
    
    [self initData];
    [self initView];
}

- (void)rightBarButtonClick {
    LimitTableViewController *limitTable = [[LimitTableViewController alloc] init];
    [self.navigationController pushViewController:limitTable animated:YES];
}

#pragma mark - Action
- (IBAction)rechargeButtonClik:(id)sender {
    if (_amoutTextField.text.doubleValue <= 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入正确的金额"];
        return;
    }
    [_amoutTextField resignFirstResponder];
    
    [self rechargeRequest];
}
- (IBAction)balanceButtonClick:(id)sender {
    _isBalanceSelect = YES;
    
    _balanceButton.selected = YES;
    _sqbButton.selected = NO;
}
- (IBAction)sqbButtonClick:(id)sender {
    _isBalanceSelect = NO;
    
    _balanceButton.selected = NO;
    _sqbButton.selected = YES;
}

- (void)changeValue:(UITextField *)textField {
    if (_amoutTextField.text.length > 0) {
        [CommonClass buttonEnableWithButton:_rechargeButton enable:YES];
    }else {
        [CommonClass buttonEnableWithButton:_rechargeButton enable:NO];
    }
}

- (IBAction)showLimit:(id)sender {
    
    [UIView animateWithDuration:0.3 animations:^{
        if (_flag == 1) {
             _flag = 0;
             self.limitView.frame = CGRectMake(0, 164.5, self.view.frame.size.width, 43);
            self.toppNumView.frame = CGRectMake(0, 219, self.view.frame.size.width, 51.5);
            self.selectToppView.frame = CGRectMake(0, 268.5, self.view.frame.size.width, 51);
            self.remindLabel.frame = CGRectMake(18, 447, self.view.frame.size.width-40, _mindHeight);
            self.rechargeButton.frame = CGRectMake(18, 373, 345, 51.5);
        }else{
            _flag = 1;
           self.limitView.frame = CGRectMake(0, 164.5, self.view.frame.size.width, 0);
           self.toppNumView.frame = CGRectMake(0, 176, self.view.frame.size.width, 51.5);
           self.selectToppView.frame = CGRectMake(0, 225.5, self.view.frame.size.width, 51);
           self.remindLabel.frame = CGRectMake(18, 404, self.view.frame.size.width-40, _mindHeight);
           self.rechargeButton.frame = CGRectMake(18, 330, 345, 51.5);
        }
       
    }];
}


#pragma mark - BaofooDelegate
- (void)callBack:(NSString*)params {
    DLOG(@"返回的参数是：%@",params); //-1失败 0取消 1成功 10处理中
    NSString * newparams = [params stringByReplacingOccurrencesOfString:@"1," withString:@""];
    NSString * params1 = [newparams stringByReplacingOccurrencesOfString:@"0," withString:@""];
    NSString * params2 = [params1 stringByReplacingOccurrencesOfString:@"-1" withString:@""];
    NSString * params3 = [params2 stringByReplacingOccurrencesOfString:@"10" withString:@""];
    //NSLog(@"%@",params3);
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:[NSString stringWithFormat:@"支付结果:%@",params3] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    
    if ([params rangeOfString:@"支付成功"].length != 0) {
//        AppDelegateInstance.isUpdateAccount = YES;
        alert.tag = 101;
    }else{
        alert.tag = 102;
    }
    [alert show];
    
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (alertView.tag==101 && buttonIndex==0) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"RechargeSuccess" object:nil];
        
        [self.navigationController popViewControllerAnimated:YES];
    }else if (alertView.tag==12 && buttonIndex==0) {
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"RechargeSuccess" object:nil];
        
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark - Data
- (void)initData {
    _isBalanceSelect = NO;
    
    [self requestData];
}

- (void)requestData {
    if (AppDelegateInstance.userInfo==nil) {
        [ReLogin outTheTimeRelogin:self];
        return;
    }
    _requestType = 1;
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:@"524" forKey:@"OPT"];
    [parameters setObject:@"" forKey:@"body"];
    [parameters setObject:AppDelegateInstance.userInfo.userId forKey:@"id"];
    
    if (_requestClient == nil) {
        _requestClient = [[NetWorkClient alloc] init];
        _requestClient.delegate = self;
    }
    [_requestClient requestGet:@"app/services" withParameters:parameters withViewController:self];
}

- (void)rechargeRequest {
    if (_isLoading) {
        [SVProgressHUD showImage:nil status:@"正在请求,请稍后再试"];
        return;
    }
    if (_rechargeAppType <= 0) {
        [SVProgressHUD showImage:nil status:@"充值方式有误！"];
        return;
    }
    
    if (_rechargeAppType == 1) {  //畅捷
        if (_isBalanceSelect) {
            _requestType = 2;
            NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
            [parameters setObject:@"519" forKey:@"OPT"];
            [parameters setObject:@"" forKey:@"body"];
            [parameters setObject:AppDelegateInstance.userInfo.userId forKey:@"id"];
            [parameters setObject:_amoutTextField.text forKey:@"money"];
            
            if (_requestClient == nil) {
                _requestClient = [[NetWorkClient alloc] init];
                _requestClient.delegate = self;
            }
            [_requestClient requestGet:@"app/services" withParameters:parameters];
        }else {
            _requestType = 3;
            NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
            [parameters setObject:@"520" forKey:@"OPT"];
            
            [parameters setObject:@"" forKey:@"body"];
            [parameters setObject:AppDelegateInstance.userInfo.userId forKey:@"userId"];
            //    NSString *password = [NSString encrypt3DES:_passwordTextField.text key:DESkey];
            //    [parameters setObject:password forKey:@"dealpwd"];
            [parameters setObject:[NSString stringWithFormat:@"%@",_amoutTextField.text] forKey:@"money"];
            
            if (_requestClient == nil) {
                _requestClient = [[NetWorkClient alloc] init];
                _requestClient.delegate = self;
            }
            [_requestClient requestGet:@"app/services" withParameters:parameters];
        }
    }else { //富友
        _requestType = 4;
        
        NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
        [parameters setObject:@"525" forKey:@"OPT"];
        [parameters setObject:@"" forKey:@"body"];
        [parameters setObject:AppDelegateInstance.userInfo.userId forKey:@"id"];
        if (_isBalanceSelect) {
            [parameters setObject:@"1" forKey:@"type"];
        }else {
            [parameters setObject:@"2" forKey:@"type"];
        }
        [parameters setObject:[NSString stringWithFormat:@"%@",_amoutTextField.text] forKey:@"amount"];
        
        if (_requestClient == nil) {
            _requestClient = [[NetWorkClient alloc] init];
            _requestClient.delegate = self;
        }
        [_requestClient requestGet:@"app/services" withParameters:parameters];
    }
    
    
}

//HTTPClientDelegate
- (void)startRequest {
    _isLoading = YES;
}

-(void) httpResponseSuccess:(NetWorkClient *)client dataTask:(NSURLSessionDataTask *)task didSuccessWithObject:(id)obj
{
    _isLoading = NO;
    NSDictionary *dics=(NSDictionary *)obj;
    DLOG(@"dic=%@",dics);
    NSString *errorStr=[NSString stringWithFormat:@"%@",[dics objectForKey:@"error"]];
    if ([errorStr isEqualToString:@"-1"]) {
        if (_requestType == 1) {
            
            _rechargeAppType = [[dics objectForKey:@"rechargeAppType"] integerValue];
            if (_rechargeAppType == 1) {
                _typeImageView.image = [UIImage imageNamed:@"baofu_logo"];
            }else if (_rechargeAppType == 2) {
                _typeImageView.image = [UIImage imageNamed:@"fuyou_logo"];
            }
            
        }else if (_requestType==2 || _requestType==3) {
            
            if (dics[@"resultReturn"] && ![dics[@"resultReturn"] isKindOfClass:[NSNull class]]) {
                NSDictionary *resultReturn = dics[@"resultReturn"];

                if ((resultReturn[@"flag"]&&![resultReturn[@"flag"] isKindOfClass:[NSNull class]]) && (resultReturn[@"outer_trade_no"]&&![resultReturn[@"outer_trade_no"] isKindOfClass:[NSNull class]]) && (resultReturn[@"uuid"]&&![resultReturn[@"uuid"] isKindOfClass:[NSNull class]])) {
                    
                    BOOL flag = [resultReturn[@"flag"] boolValue];
                    NSString *outer_trade_no = [NSString stringWithFormat:@"%@",resultReturn[@"outer_trade_no"]];
                    NSString *uuid = [NSString stringWithFormat:@"%@",resultReturn[@"uuid"]];
                    if (flag && outer_trade_no.length>0 && uuid.length>0) {
                        RechargeVerifyViewController *verify = [[RechargeVerifyViewController alloc] init];
                        verify.uuidStr = uuid;
                        verify.tradeNoStr = outer_trade_no;
                        [self.navigationController pushViewController:verify animated:YES];
                        
                    }else {
                        NSString *str = [dics objectForKey:@"retMsg"];
                        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:str delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                        [alert show];
                    }
                }else {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"参数有误!" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                    [alert show];
                }
            }else {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"参数有误!" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alert show];
            }
            

           
            
            /*
            if ([[dics objectForKey:@"retCode"] isEqualToString:@"0000"]) {
                BaoFooPayController*web = [[BaoFooPayController alloc] init];
                web.PAY_TOKEN = [dics objectForKey:@"tradeNo"];
                web.delegate = self;
                if (!kIsTestEnvironment) {
                    web.PAY_BUSINESS = @"true";
                    DLOG(@"正式环境");
                }else {
                    web.PAY_BUSINESS = @"fals";
                    DLOG(@"测试环境");
                }
                [self presentViewController:web animated:YES completion:^{
                }];
            }
            else
            {
                NSString*str = [dics objectForKey:@"retMsg"];
                if (!str) {
                    str = @"创建订单号失败";
                }
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:str delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alert show];
            }*/
            
        }else if (_requestType == 4) {
            
            
            
            NSString * myVERSION = [NSString stringWithFormat:@"2.0"] ;     //SDK 接口版本参数  定值
            NSString * myMCHNTCD = [NSString stringWithFormat:@"%@",dics[@"MCHNTCD"]]; // 商户号
            NSString * myMCHNTORDERID = [NSString stringWithFormat:@"%@",dics[@"MCHNTORDERID"]]; // 商户订单号
            NSString * myUSERID = [NSString stringWithFormat:@"%@",dics[@"USERID"]]; // 用户编号
            NSString * myAMT = [NSString stringWithFormat:@"%@",dics[@"AMT"]];  // 金额
            NSString * myBANKCARD = [NSString stringWithFormat:@"%@",dics[@"BANKCARD"]]; // 银行卡号
            NSString * myBACKURL = [NSString stringWithFormat:@"%@",dics[@"BACKURL"]]; // 回调地址
            
            NSString * myNAME = [NSString stringWithFormat:@"%@",dics[@"NAME"]] ; // 姓名
            NSString * myIDNO = [NSString stringWithFormat:@"%@",dics[@"IDNO"]] ; // 证件编号
            NSString * myIDTYPE = [NSString stringWithFormat:@"%@",dics[@"IDTYPE"]] ; // 证件类型(目前只支持身份证)
            NSString * myTYPE = [NSString stringWithFormat:@"%@",dics[@"TYPE"]] ;
            NSString * mySIGNTP = [NSString stringWithFormat:@"%@",dics[@"SIGNTP"]] ;
            NSString * myMCHNTCDKEY = [NSString stringWithFormat:@"%@",dics[@"MCHNTCDKEY"]] ;//商户秘钥
            
            
//            NSString * mySIGN = [NSString stringWithFormat:@"%@|%@|%@|%@|%@|%@|%@|%@|%@|%@|%@|%@" , myTYPE,myVERSION,myMCHNTCD,myMCHNTORDERID,myUSERID,myAMT,myBANKCARD,myBACKURL,myNAME,myIDNO,myIDTYPE,myMCHNTCDKEY] ;
            NSString * mySIGN = [NSString stringWithFormat:@"%@",dics[@"SIGN"]];
            //NSLog(@"sign = %@",mySIGN) ;
            //mySIGN = [mySIGN MD5String] ;                         //签名字段
            
            //添加环境参数  BOOL 变量 @"TEST"   YES 是测试  NO     是生产。  使用生产环境时 ，请传入真实信息，并替换生产商户号和秘钥
            
            //富友提供测试用的生产环境商户号和秘钥 ： mchntcd : 0002900F0280321       key : fx45crzkmo8akn24plwvrv8ywd10zjuy
            //测试商户号和秘钥                    mchntcd : 0002900F0096235       key : 5old71wihg2tqjug9kkpxnhx9hiujoqj
            BOOL test = kIsTestEnvironment;
            NSNumber * testNumber = [NSNumber numberWithBool:test] ;
            NSDictionary * dicD = @{@"TYPE":myTYPE,@"VERSION":myVERSION,@"MCHNTCD":myMCHNTCD,@"MCHNTORDERID":myMCHNTORDERID,@"USERID":myUSERID,@"AMT":myAMT,@"BANKCARD":myBANKCARD,@"BACKURL":myBACKURL,@"NAME":myNAME,@"IDNO":myIDNO,@"IDTYPE":myIDTYPE,@"SIGNTP":mySIGNTP,@"SIGN":mySIGN , @"TEST" : testNumber} ;
            //NSLog(@"😄dicD =%@ " , dicD) ;
            
#if TARGET_IPHONE_SIMULATOR
            [SVProgressHUD showErrorWithStatus:@"亲，模拟器不可运行哦~"];
            
#elif TARGET_OS_IPHONE
            FUMobilePay * pay = [FUMobilePay shareInstance];
            if([pay respondsToSelector:@selector(mobilePay:delegate:)])
                [pay performSelector:@selector(mobilePay:delegate:) withObject:dicD withObject:self];
            
#endif

            
            
        }
        
    }else if ([[NSString stringWithFormat:@"%@",[dics objectForKey:@"error"]] isEqualToString:@"-2"]) {
        
        [ReLogin outTheTimeRelogin:self];
    }else{
        [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",[dics objectForKey:@"msg"]]];
    }
}

-(void) httpResponseFailure:(NetWorkClient *)client dataTask:(NSURLSessionDataTask *)task didFailWithError:(NSError *)error {
    _isLoading = NO;
    if (_requestType != 1) {
        [SVProgressHUD showErrorWithStatus:@"连接服务器失败，请稍后再试"];
    }
}

-(void) networkError {
    _isLoading = NO;
    if (_requestType != 1) {
        [SVProgressHUD showErrorWithStatus:@"网络不给力，请检查您的网络设置"];
    }
}

#pragma mark ------支付结果回调------
- (void)payCallBack:(BOOL)success responseParams:(NSDictionary *)responseParams
{
    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"提示" message:responseParams[@"RESPONSEMSG"] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil] ;
    if (success) {
        alert.tag = 12;
    }
    [alert show] ;
}

#pragma mark - View
- (void)initView {
    _typeValue.font = KFontSize(14);
    _amoutValue.font = KFontSize(14);
    _amoutTextField.font = KFontSize(14);
    _moneyTypeValue.font = KFontSize(14);
    _sqbButton.titleLabel.font = KFontSize(15);
    _balanceButton.titleLabel.font = KFontSize(15);
    _rechargeButton.titleLabel.font = KFontSize(15);
    _remindLabel.font = KFontSize(14);
    _cardTypeLabel.font = KFontSize(14);
    _bankCardLabel.font = KFontSize(13);
    _bankNameLabel.font = KFontSize(14);
    _rechargeButton.clipsToBounds = YES;
    _rechargeButton.layer.cornerRadius = kCornerRadius;
    _amoutTextField.delegate = self;
    [_amoutTextField addTarget:self action:@selector(changeValue:) forControlEvents:UIControlEventEditingChanged];
    
    if (self.viewType == 1) {
        [self balanceButtonClick:_balanceButton];
    }
    
    
    self.limitView.frame = CGRectMake(0, 164.5, self.view.frame.size.width, 0);
    self.toppNumView.frame = CGRectMake(0, 176, self.view.frame.size.width, 51.5);
    self.selectToppView.frame = CGRectMake(0, 225.5, self.view.frame.size.width, 51);
    self.rechargeButton.frame = CGRectMake(18, 330, 345, 51.5);
    _scrollView.contentSize = CGSizeMake(0, GetMaxY(_remindLabel) + 50);
    NSString *mindStr = [NSString stringWithFormat:@"%@",@"*转账提示：\n1.每日凌晨两点统一发放前一日利息。\n\n2.单日充值金额超过5万的客户，可在网页版选择网银U盾方式充值。\n\n3.额度表仅作参考，单日限额以各家银行实际额度为准。"];
     _mindHeight = [MyTools getSizeOfString:mindStr maxWidth:MSWIDTH - 20 maxHeight:1000 withFontSize:14].height + 5;
    self.remindLabel.frame = CGRectMake(18, 404, self.view.frame.size.width-40, _mindHeight);
    self.remindLabel.attributedText = [MyTools getNSMutableAttributedStringWithText:mindStr start:0 end:1 textColor:KColor textFont:KFontSize(14)];
}

- (void)viewDidLayoutSubviews {
    CGRect frame = _remindLabel.frame;
    frame.origin.y = GetMaxY(_rechargeButton) + KAdaptNum(16);;
    _remindLabel.frame = frame;
    
    _scrollView.contentSize = CGSizeMake(0, GetMaxY(_remindLabel) + 50);
}

#pragma mark - 返回
- (void)back {
    if (self.backType == 1) {
        [self.navigationController popToRootViewControllerAnimated:YES];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
